<%@ page contentType="text/html;charset=UTF-8"%>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
	content="initial-scale=1, maximum-scale=1, user-scalable=no">
<meta name="format-detection" content="telephone=no">
<title>取票退票页面</title>
<link rel="stylesheet" href="${ctx}/static/plug/weui/css/weui.css"
	media="all">

<link rel="stylesheet" href="${ctx}/static/plug/weui/css/weuix.css"
	media="all">
	
	<link rel="stylesheet" href="${ctx}/static/css/sellticket/userTicket.css"
	media="all">
<style type="text/css">
</style>



</head>
<body>
	<div class="header">
		<p>${modeType == 1 ? "取票" : "退票"}
		</p>
		<div class="datetime">
			<span class="times"></span> <span>${user.entNo}，你好</span>
		</div>
		<div class="tips">
			 <span>当前设备连接失败</span>
		</div>
		
	</div>
		<p align="center">确认信息</p>
		<input type="hidden" value="${modeType}" id="modeType">
		<input type="hidden" value="${user.scenicSpotId}" id="scenicSpotId">
	<div class="subjects">
	
	<c:if test="${ resultMap.ticketOrderDetailVoList == null || fn:length(resultMap.ticketOrderDetailVoList) == 0 }">
		<h1 align="center">暂无票务信息,正在回跳。。。</h1>
	</c:if>
	
	
		<c:forEach var="ticketOrder"  varStatus=""  items="${resultMap.ticketOrderDetailVoList}">
		<div class="weui-form-li">
			 <input class="weui-form-checkbox" name="f4" id="${ticketOrder.id }" checked="checked" value="美术" type="checkbox">
		<label for="${ticketOrder.id }" class="labels">
                <i class="weui-icon-checkbox"></i>
			<div id="ticket_purchase" class="weui-form-text">
				<p class="textP">票<span class="blank"></span>码：${ticketOrder.checkCode}</p>
				<p class="textP">姓<span class="blank"></span>名：${ticketOrder.userName}</p>
				<p class="textP">有效次数：${ticketOrder.effectiveNum == 3 ? "无限制" : "1次（验票后失效）"}</p>
				<p class="textP">起效时间：${ticketOrder.entryTimeStr}</p>
				<p class="textP">到期时间：${ticketOrder.validTimeStr}</p>
				<p class="textP">状<span class="blank"></span>态：${ticketOrder.printStatus == 0 ? "未打印" : "已打印"}</p>
				<p class="textP">票<span class="blank"></span>价：￥${ticketOrder.prices/100}元</p>
			</div>
		 </label>
		 </div>
		</c:forEach>
	</div>
	
	
	
		<div align="center" id="manual"><p><span id="returns">返回</span>
		<c:if test="${modeType == 1 && resultMap.ticketOrderDetailVoList != null && fn:length(resultMap.ticketOrderDetailVoList) > 0}">
			<span id="prints">打印</span>
		</c:if>
		
		<c:if test="${modeType == 2 && resultMap.ticketOrderDetailVoList != null && fn:length(resultMap.ticketOrderDetailVoList) > 0}">
			<span id="refundTicket">退票</span>
		</c:if>	
		</p>
		</div>
		<br>
		<br>
		<br>
		<br>
		<br>
		<br>
		<br>
	<div class="tailer">
		
		<div class="returns">
			<p id="return">回到首页</p>
		</div>
		
		<div class="returns">
				<p id="refund">退票</p>
			</div>
			
			<div class="returns">
				<p id="collection">取票</p>
			</div>
			
			<div class="returns">
				<p id="sell">售票</p>
			</div>
		
	</div>
	
</body>












<script src="${ctx}/static/js/jquery/jquery.min.js"></script>
<script src="${ctx}/static/js/jquery/aes.js"></script>
<script src="${ctx}/static/plug/weui/js/zepto.weui.js"
	type="text/javascript"></script>
<script src="${ctx}/static/plug/weui/js/zepto.min.js"
	type="text/javascript"></script>


<script>
var socket;
var deviceSubmission = false;
	$(function() {
		var index = ${resultMap.ticketOrderDetailVoList == null ? 0 : fn:length(resultMap.ticketOrderDetailVoList)};
		if(index == 0){
			setTimeout(function () {
				var modeType = $("#modeType").val();
				window.location.href="${ctx}/takeOrRetreat/toCheckCodePick?modeType="+modeType;
			}, 3000);
		}
		
		
		
		
		$("#sell").click(function() {
			var scenicSpotId = $("#scenicSpotId").val();
			window.location.href="${ctx}/selling/toVoteTicket?scenicSpotId=" + scenicSpotId;
		});
		
		$("#collection").click(function() {
			window.location.href="${ctx}/takeOrRetreat/toCheckCodePick?modeType=" + 1;
		});
		
		$("#refund").click(function() {
			window.location.href="${ctx}/takeOrRetreat/toCheckCodePick?modeType="  + 2;
		});
		
		
		var submission = true;
		$("#refundTicket").click(function() {
			if(!submission){
				return;
			}
			var orderDetailIdList = new Array();
			for (var i = 0; i < $(".weui-form-checkbox").length; i++) {
				if($(".weui-form-checkbox").eq(i).prop("checked")){
					var orderDetailId = $(".weui-form-checkbox").eq(i).attr("id")
					console.log(orderDetailId);
					orderDetailIdList.push(orderDetailId)
				}
			}
			console.log(orderDetailIdList);
			var params = {
					"orderDetailIdList" : JSON.stringify(orderDetailIdList)
			}
			console.log(params);
			submission = false;
			$.post("${ctx}/takeOrRetreat/refundTicket",params  , function(obj) {
				submission = true;
				if(obj.result){
					$.alert(obj.msg,"标题",function(){
						$("#returns").click();
					});
				}
        	});
			
		});
		
		var printNums = 0;
		var printNumVal = 0;
		var printNumTatol = 0;
		webSocketConnect();
		function webSocketConnect() {
			if(localStorage.serverIP != null || localStorage.serverPort != null){
				var serverIP = localStorage.serverIP;
		   		var serverPort = localStorage.serverPort;
		   		var host = "ws://" + serverIP + ":" + serverPort + "/"
		        socket = new WebSocket(host);
		   	 	try {
	           	  socket.onopen = function (msg) {
	           		 $(".tips").css("display","none")
	           		 deviceSubmission = true;
	            	};
	              socket.onmessage = function (msg) {
	                if (typeof msg.data == "string") {
	                		console.log(msg)
	                		console.log(msg.data)
	                		var data = $.parseJSON(msg.data);
	                		console.log(data)
							if(data.code == "000"){
								var data = data.data;
								console.log(data)
								if(data.print_result == "000000"){
									var params = {
											"orderDetailId":data.ticket_id
										}
									$.post("${ctx}/takeOrRetreat/printTicket",params  , function(obj) {
										if(obj.result){
											printNumVal++;
											console.log(printNumVal);
											console.log(printNumTatol);
											if(printNumVal == printNumTatol){
												window.location.reload();
											}
										}else {
											submission = true;
											$.toast(obj.msg, "forbidden");
										}
							        });
								}else if(data.print_result == "111111"){
									$.toast(data.print_status, "forbidden");
								}
	                		}
	                		
							if(data.code == "001"){
								var deviceId = data.device_id;
								localStorage.deviceNo = deviceId;
	                			var resultStr =  data.data.qrcode;
	                			resultStr = JSON.parse(aesHexDecrypt(resultStr));
	                			if(resultStr.orderId){
	                				orderId  = resultStr.orderId;
	                			}
	                			if(resultStr.checkCode){
	                				var checkCode  = resultStr.checkCode;
	                    			$("#checkCode").val(checkCode);
	                    			return
	                    			
	                			}
	                			$.alert("无效二维码！","提示",function(){});
	                			console.log(orderId);
	                		}
	                		
	                		if(data.code == "002"){
								var deviceId = data.device_id;
								var resultStr = data.data;
								console.log(resultStr);
								var name = resultStr.name;
								var idNumber = resultStr.cid;
								console.log(name + "   :   " + idNumber);
								$("#checkCode").val(idNumber);
	                		}
		                }
		                else {
		                    alert("非文本消息");
		                }
	            	};
	              socket.onclose = function (msg) { 
	            	  $.confirm("连接设备失败是否继续连接", "提示", function() {
	              		 webSocketConnect();
	                   }, function() {
	                       //取消操作
	                       $(".tips").css("display","block")
	                       deviceSubmission = false;
	                   });
	           		  };
	        	}catch (ex) {
		            log(ex);
		            webSocketConnect();
	        	}
			}else {
				$(".tips").css("display","block")
				deviceSubmission = false;
			}
		};

		$("#prints").click(function() {
			if(!deviceSubmission){
				$.toast("设备未连接成功无法使用", "forbidden");
				return;
			}
			
			if(!submission){
				return;
			}
			var orderDetailIdList = new Array();
			submission = false;
			printNumTatol = $(".weui-form-checkbox").length;
			for (var i = 0; i < $(".weui-form-checkbox").length; i++) {
				if($(".weui-form-checkbox").eq(i).prop("checked")){
					var orderDetailId = $(".weui-form-checkbox").eq(i).attr("id")
					console.log(orderDetailId);
					orderDetailIdList.push(orderDetailId);
					var params = {
							"orderDetailId" : orderDetailId
					}
					$.ajaxSettings.async = false;
					$.post("${ctx}/takeOrRetreat/getTicket",params  , function(obj) {
						if(obj.result){
							var ticketOrderDetailVo = obj.ticketOrderDetailVo;
							delete ticketOrderDetailVo["insertMap"];
							delete ticketOrderDetailVo["qrCode"];
							delete ticketOrderDetailVo["printTime"];
							delete ticketOrderDetailVo["createTime"];
							delete ticketOrderDetailVo["entryTime"];
							delete ticketOrderDetailVo["lastVerifyTime"];
							delete ticketOrderDetailVo["updateTime"];
							delete ticketOrderDetailVo["validTime"];
							console.log(ticketOrderDetailVo);
							var cmd = {
									"cmd":"print",
									"qrcode_val":ticketOrderDetailVo.checkCode,
									"qrcode_img":ticketOrderDetailVo.qrCodeStr,
									"ticket_id":ticketOrderDetailVo.id,
									"ticket_Val" : ticketOrderDetailVo
							};
							console.log(cmd);
							socket.send(JSON.stringify(cmd));
						}
		        	});
				}
			}
			return;
		});
		
		getNowFormatDate();
		$("#returns").click(function() {
			var modeType = $("#modeType").val();
			window.location.href="${ctx}/takeOrRetreat/toCheckCodePick?modeType="+modeType;
		});
		$("#return").click(function() {
			window.location.href="${ctx}/selling/index";
		});
		
		
	});
	
	function aesHex(src) {
		var key = CryptoJS.enc.Utf8.parse("fb18fc197e644d38");
		var encrypted = CryptoJS.AES.encrypt(src, key, {
			 mode: CryptoJS.mode.ECB,
		     padding: CryptoJS.pad.Pkcs7
		});
		return encrypted.ciphertext.toString();
	}
	
	
	function aesHexDecrypt(src) {
		var key = CryptoJS.enc.Utf8.parse("fb18fc197e644d38");
		console.log(src)
		console.log(CryptoJS.enc.Utf8.parse(src))
		var encryptedBase64Str = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Hex.parse(src));
		console.log(encryptedBase64Str)
	    var decryptedData = CryptoJS.AES.decrypt(encryptedBase64Str, key, {
	    	mode: CryptoJS.mode.ECB,
		    padding: CryptoJS.pad.Pkcs7
	    });
		console.log(decryptedData)
	    var decryptedStr = decryptedData.toString(CryptoJS.enc.Utf8);
		console.log(decryptedStr)
		return decryptedStr;
	}
	
	function getNowFormatDate() {
	    var date = new Date();
	    var seperator1 = "-";
	    var seperator2 = ":";
	    var month = date.getMonth() + 1;
	    var strDate = date.getDate();
	    var secondStr = date.getSeconds();
		var minuteStr = date.getMinutes();
		var hourStr = date.getHours();
	    if (month >= 1 && month <= 9) {
	        month = "0" + month;
	    }
	    if (strDate >= 0 && strDate <= 9) {
	        strDate = "0" + strDate;
	    }
	    if (secondStr >= 0 && secondStr <= 9) {
			secondStr = "0" + secondStr;
		}
		if (minuteStr >= 0 && minuteStr <= 9) {
			minuteStr = "0" + minuteStr;
		}
		if (hourStr >= 0 && hourStr <= 9) {
			hourStr = "0" + hourStr;
		}
		
		var currentdate = date.getFullYear() + seperator1 + month + seperator1
		+ strDate + " " + hourStr + seperator2 + minuteStr
		+ seperator2 + secondStr;
	    $(".times").text(currentdate);
	    setTimeout(getNowFormatDate, 1000);
	}
</script>


</html>